package com.sfac.springBoot.modules.test.service.impl;

import com.sfac.springBoot.modules.common.vo.Result;
import com.sfac.springBoot.modules.common.vo.Search;
import com.sfac.springBoot.modules.test.dao.StudentDao;
import com.sfac.springBoot.modules.test.entity.Student;
import com.sfac.springBoot.modules.test.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @Description StudentService
 * @Author HymanHu
 * @Date 2022/7/1 15:00
 */
@Service
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentDao studentDao;

	@Override
	@Transactional
	public Result<Student> editStudent(Student student) {
		studentDao.saveAndFlush(student);
		return new Result<>(Result.ResultStatus.SUCCESS.code, "更新成功.", student);
	}

	@Override
	public Student getStudentById(int id) {
		return studentDao.getById(id);
	}

	@Override
	public Student getStudentByStudentName(String studentName) {
		List<Student> list = Optional
				.ofNullable(studentDao.findByStudentName(studentName))
				.orElse(Collections.emptyList());
		return list.isEmpty() ?  null : list.get(0);
	}

	@Override
	@Transactional
	public Result<Student> updateStudent(Student student) {
		studentDao.updateStudent(student);
		return new Result<>(Result.ResultStatus.SUCCESS.code, "修改成功.", student);
	}

	@Override
	public Page<Student> getStudentsBySearch(Search search) {
		Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
		Sort sort = Sort.by(order);
		Pageable pageable = PageRequest.of(search.getCurrentPage() - 1, search.getPageSize(), sort);

		Student student = new Student();
		student.setStudentName(search.getKeyword());
		ExampleMatcher matcher = ExampleMatcher.matchingAny()
				.withMatcher("studentName", match -> match.contains())
				.withIgnorePaths("id", "age");
		Example<Student> example = Example.of(student, matcher);

		return studentDao.findAll(example, pageable);
	}
}
